import axios from 'axios'
import type {AxiosRequestConfig} from 'axios'
import {ElMessage} from 'element-plus'

const passLsit = ['/api/blog/searchMyblog', '/api/user/signin'] // message白名单 需要登录才能操作的接口特殊情况下不用弹出提示


type postType = {
    errno: number
    message?: string
    data?: any
}
class Server {
    private config: AxiosRequestConfig = {
        headers: {'Content-Type': 'application/json'},
        timeout: 30000,
        responseType: 'json'
    }

    get(url: string, query?: any, option?: AxiosRequestConfig):Promise<postType> {
        return new Promise((resove, reject) => {
            let config: any = {}
            if(query) {
                config.params = query
            }
            config = {...config, ...this.config, ...option}
            axios.get(url, config).then(res => {
                if(res.data.errno === 1 && res.data?.message === '未登录') {
                    // message白名单处理
                    if(!passLsit.includes(url.split('?')[0])){
                        // 未登录处理
                        ElMessage .error(res.data.message)
                    }
                }
                resove(res.data)
            }).catch(err => {
                reject(new Error(err))
            })
        })
    }

    post(url: string, data?: any, option?: AxiosRequestConfig):Promise<postType> {
        return new Promise((resove, reject) => {
            let config: any = {}
            config = {...config, ...this.config, ...option}
            axios.post(url, data, config).then(res => {
                if(res.data.errno === 1 && res.data?.message === '未登录') {
                    // 未登录处理
                    if(!passLsit.includes(url.split('?')[0])){
                        // 未登录处理
                        ElMessage .error(res.data.message)
                    }
                }
                resove(res.data)
                
            }).catch(err => {
                reject(new Error(err))
            })
        })
       
    }
}
const Fetch = new Server()
export default Fetch
